package com.yupi.springbootinit.biz.impl;


import com.yupi.springbootinit.biz.TaskBiz;
import com.yupi.springbootinit.model.entity.Task;
import com.yupi.springbootinit.model.vo.TaskModel;
import com.yupi.springbootinit.model.vo.TaskReq;
import com.yupi.springbootinit.model.vo.TaskVO;
import com.yupi.springbootinit.service.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TaskBizImpl implements TaskBiz {

    @Autowired
    private TaskService taskService;

    @Override
    public List<TaskModel> queryList(TaskReq req) {
        List<Task> list;
        if (req == null || (StringUtils.isBlank(req.getTaskName()) &&
                StringUtils.isBlank(req.getVersion()) && req.getTaskDate() == null)) {
            list = taskService.listByReq(new Date(), null);
        } else {
            list = taskService.listByReq(req.getTaskDate(), req.getVersion());
        }
        return getTaskModels(list);
    }

    @Override
    public void update(TaskReq req) {
        taskService.updateByTaskCode(req);
    }

    @Override
    public List<String> getTaskVersion() {
        return taskService.getTaskVersion();
    }

    private static @NotNull ArrayList<TaskModel> getTaskModels(List<Task> list) {
        List<TaskVO> collect1 = list.stream().map(x -> {
            TaskVO taskVO = new TaskVO();
            BeanUtils.copyProperties(x, taskVO);
            taskVO.setId(taskVO.getId());
            return taskVO;
        }).collect(Collectors.toList());
        Map<String, List<TaskVO>> collect = collect1.stream().collect(Collectors.groupingBy(TaskVO::getVersion));
        ArrayList<TaskModel> taskVOS = new ArrayList<>();
        for (Map.Entry<String, List<TaskVO>> stringListEntry : collect.entrySet()) {
            TaskModel taskModel = new TaskModel();
            List<TaskVO> value = stringListEntry.getValue();
            taskModel.setRecord(value);
            String key = stringListEntry.getKey();
            taskModel.setVersion(key);
            taskVOS.add(taskModel);
        }
        return taskVOS;
    }


}
